package cz.data.domain.standard.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cz.data.common.core.RedisConstant;
import cz.data.common.redis.service.RedisService;
import cz.data.domain.standard.dao.DictDao;
import cz.data.domain.standard.model.entity.DictEntity;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class SpringEventListener {

    @EventListener(ApplicationReadyEvent.class)
    public void applicationReady(ApplicationReadyEvent event) {
        ConfigurableApplicationContext context = event.getApplicationContext();
        DictDao dictDao = context.getBean(DictDao.class);
        RedisService redisService = context.getBean(RedisService.class);
        // 项目启动时，初始化缓存
        String dictKey = RedisConstant.STANDARD_DICT_KEY;
        Boolean hasDictKey = redisService.hasKey(dictKey);
        if (!hasDictKey) {
            List<DictEntity> dictEntityList = dictDao.selectList(Wrappers.emptyWrapper());
            Map<String, List<DictEntity>> dictListMap = dictEntityList.stream()
                    .collect(Collectors.groupingBy(DictEntity::getTypeId));
            redisService.hmset(dictKey, new HashMap<>(dictListMap));
        }
    }
}
